// pages/addressList/addressList.js
const addressService = require('../../../../../api/addressService.js')
var QQMapWX = require('../../../../../libs/qqmap-wx-jssdk.min.js');
var qqmapsdk;


//获取应用实例
const app = getApp()

Page({

	/**
	 * 页面的初始数据
	 */
  data: {
    addressList: [],
    isDelete: false,
    isDeleteId: '',
    isDeleteText: "删除地址",
    currentItem: -1,
    searchLabelShow: false,
    currentAddress: "",
    nearbyAddress: [],
    chooseAddress: false,
    searchText: '搜索收货地址'
  },
  // 搜索框点击事件,输入框聚焦
  handleFocus: function (e) {
    this.setData({
      searchLabelShow: true
    })
  },
  // 搜索框失去焦点处理
  handleBlur: function (e) {
    this.setData({
      searchLabelShow: false
    })
  },
  // 刷新操作
  handleRefresh: function () {
    this.getAddressList(this)
  },
  // 获取当前地理坐标，然后获取附近的地址
  getAddressList(self) {
    wx.showLoading({
      title: '加载中',
    })
    //1、获取当前位置坐标
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        var latitude = res.latitude
        var longitude = res.longitude
        //2、根据坐标获取当前位置名称，显示在顶部:腾讯地图逆地址解析
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: latitude,
            longitude: longitude
          },
          get_poi: 1,
          success: function (res) {
            self.setData({
              currentAddress: res.result.formatted_addresses.recommend, // 获取经过腾讯地图优化过的地理位置描述
              nearbyAddress: res.result.pois // 获取附近poi列表
            })
            wx.hideLoading()
          },
          fail: function (res) {
            console.log(res);
          }
        })
      }
    })
  },
  // 监听搜索框输入
  handleInput: function (e) {
    if (!e.detail.value) {
      this.handleRefresh()
    }
  },
  // 地址点击选择操作
  clickAddress: function (val) {
    const id = val.currentTarget.dataset.id
    const nearbyAddress = this.data.nearbyAddress
    let locationInfo = {}
    if (nearbyAddress.length > 0) {
      nearbyAddress.forEach(item => {
        if (item.id === id) {
          locationInfo = {
            ...item
          }
        }
      })
    }
    try {
      wx.setStorageSync('wj_locationInfo', locationInfo)
    } catch (e) {
    }
    wx.navigateTo({
      url: '../addAddress/addAddress'
    })
  },
  // 搜索框搜索根据关键字搜索地址
  handleConfirm(val) {
    var self = this;
    if (!val.detail.value) {
      self.handleRefresh()
    } else {
      qqmapsdk.search({
        keyword: val.detail.value,
        success: function (res) {
          console.log(res);
          self.setData({
            nearbyAddress: res.data
          })
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }
  },
  // 跳转添加地址
  toAddAddress: function () {
    const loginStatus = this.checkAuth()
    if (loginStatus) {
      wx.navigateTo({
        url: '../addAddress/addAddress'
      })
    } else {
      wx.showToast({
        title: '请登录后再添加地址哦~',
        icon: 'none',
        duration: 2000
      })
    }
  },
  // 检查当前用户是否登录授权
  checkAuth: function () {
    if (!app.globalData.userInfo) {
      return false;
    } else {
      return true;
    }
  },
	/**
	 * 修改地址
	 */
  editAddress: function (item) {
    console.log("1")
    let addressId = item.target.dataset.id
    try {
      let addressSelect = {
        id: addressId,
      }
      wx.setStorageSync('wj_editAddress', addressSelect)
    } catch (e) {
      console.log(1)
    }
    wx.navigateTo({
      url: '../addAddress/addAddress?doEditAddress=edit'
    })
  },
  // 处理地址选择点击事件
  handleChoose: function (e) {
    const that = this
    console.log(this.options)
    if (this.options.from == 'perfectOrder') {
      //从完善订单页进来选择地址
      if (that.data.isDelete) {
        // 删除
        var index = e.currentTarget.dataset.index;
        let addressId = e.currentTarget.dataset.id
        console.log(addressId)
        if (that.data.currentItem !== index) {
          that.setData({
            isDeleteId: addressId,
            currentItem: index
          })
        } else {
          that.setData({
            isDeleteId: addressId,
            currentItem: -1
          })
        }
      } else {
        // 普通点击
        console.log(e)
        let chooseAddress = '';
        this.data.addressList.forEach(ele => {
          if (ele.id === e.currentTarget.dataset.id) {
            chooseAddress = ele;
          }
        });
        try {
          wx.setStorageSync('wj_chooseAddressInfo', chooseAddress)
        } catch (e) { }
        wx.navigateBack({
          delta: 1
        })
      }
    } else {
      var index = e.currentTarget.dataset.index;
      let addressId = e.currentTarget.dataset.id
      console.log(addressId)
      if (this.data.currentItem !== index) {
        that.setData({
          isDeleteId: addressId,
          currentItem: index
        })
      } else {
        that.setData({
          isDeleteId: addressId,
          currentItem: -1
        })
      }
    }
  },

	/**
	 * 删除地址
	 */
  bindDelete: function () {
    if (this.data.isDelete == false) {
      this.setData({
        isDelete: true,
        isDeleteText: "取消",
        currentItem: -1
      })
    } else {
      this.setData({
        isDelete: false,
        isDeleteText: "删除地址"
      })
    }
  },
  doDeleteAddress: function () {
    const that = this
    var id = this.data.isDeleteId
    if (id && id != '') {
      addressService.removeById(id).then(res => {
        console.log(res)
        that.queryAddress()
        that.setData({
          isDeleteId: '',
          currentItem: -1
        })
        wx.showToast({
          title: "删除成功~",
          icon: 'none',
          duration: 2000
        })
        try {
          var value = wx.getStorageSync('wj_chooseAddressInfo')
          if (value) {
            if (value.id === id) {
              wx.removeStorageSync('wj_chooseAddressInfo')
            }
          }
        } catch (e) {
          // Do something when catch error
        }
      })
    } else {
      wx.showToast({
        title: "请选择要删除的地址~",
        icon: 'none',
        duration: 2000
      })
    }
  },
  queryAddress: function () {
    const loginStatus = this.checkAuth()
    if (loginStatus) {
      addressService.query().then(res => {
        console.log(res)
        let tempList = []
        if (res && res.length > 0) {
          res.forEach(item => {
            let tempItem = {
              ...item,
              gender: item.gender === 'MALE'
            }
            if (item.gender === 'MALE') {
              tempItem = {
                ...item,
                gender: '先生'
              }
            } else if (item.gender === 'FEMALE') {
              tempItem = {
                ...item,
                gender: '女士'
              }
            } else {
              tempItem = {
                ...item,
                gender: ''
              }
            }
            tempList.push(tempItem)
            if (item.defaultAddress) {
              let chooseAddress = tempItem;
              try {
                wx.setStorageSync('wj_chooseAddressInfo', chooseAddress)
              } catch (e) { }
            }
          })
        }
        this.setData({
          addressList: tempList
        })
      }).catch(err => {
        wx.showToast({
          title: err.message,
          icon: 'none',
          duration: 2000
        })
      })
    } else {

    }
  },

	/**
	 * 生命周期函数--监听页面加载
	 */
  onLoad: function (options) {
    wx.hideShareMenu()
    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: 'AD5BZ-CHCKS-64OOD-6G6TX-BSOA6-IFF3V'
    });
    if (options.from === 'perfectOrder') {
      wx.setNavigationBarTitle({
        title: '地址选择'
      })
      if (app.globalData.userInfo.member) {
        this.getAddressList(this);
        this.setData({
          chooseAddress: true
        })
      } else {

      }
    }
  },

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
  onReady: function () {

  },

	/**
	 * 生命周期函数--监听页面显示
	 */
  onShow: function () {
    wx.hideShareMenu()
    if (app.globalData.userInfo.member) {
      this.queryAddress()
    } else {
      wx.showToast({
        title: '您还不是会员，请先绑定手机号码成为会员',
        icon: 'none',
        duration: 2000
      })
    }
  },

	/**
	 * 生命周期函数--监听页面隐藏
	 */
  onHide: function () {

  },

	/**
	 * 生命周期函数--监听页面卸载
	 */
  onUnload: function () {

  },

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
  onPullDownRefresh: function () {

  },

	/**
	 * 页面上拉触底事件的处理函数
	 */
  onReachBottom: function () {

  },

	/**
	 * 用户点击右上角分享
	 */
  onShareAppMessage: function () {

  },
  // 检查当前用户是否登录授权
  checkAuth: function () {
    if (!app.globalData.userInfo) {
      return false;
    } else {
      return true;
    }
  },
})